package dao

import (
	"SE/global"
	"SE/model"
	"fmt"
	"golang.org/x/crypto/bcrypt"
)

var users []model.User

// GetUserListDao GetUserList 获取用户列表(page第几页,page_size每页几条数据)
func GetUserListDao(page int, page_size int) (int, []interface{}) {
	// 分页用户列表数据
	userList := make([]interface{}, 0, len(users))
	// 计算偏移量
	offset := (page - 1) * page_size
	// 查询所有的user
	result := global.DB.Offset(offset).Limit(page_size).Find(&users)
	// 查不到数据时
	if result.RowsAffected == 0 {
		return 0, userList
	}
	// 获取user总数
	total := len(users)
	// 查询数据
	result.Offset(offset).Limit(page_size).Find(&users)
	//
	for _, useSingle := range users {
		userItemMap := map[string]interface{}{
			"id":       useSingle.ID,
			"username": useSingle.UserName,
			"password": useSingle.Password,
			"address":  useSingle.Address,
			"mobile":   useSingle.Mobile,
		}
		userList = append(userList, userItemMap)
	}
	return total, userList
}

var user model.User

// FindUserInfo UsernameFindUserInfo 通过username找到用户信息
func FindUserInfo(mobile string, password string) (*model.User, bool) {

	rows := global.DB.Where("mobile = ?", mobile).First(&user)
	fmt.Println("rows.RowsAffected", rows.RowsAffected)
	if rows.RowsAffected < 1 {
		return &user, false
	}
	fmt.Println("user", user)
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		return &user, false
	}
	return &user, true
}

var manager model.Manager

func FindUserInfoByMobile(mobile string, code int) bool {
	rows := global.DB.Where("mobile = ? and code = ?", mobile, code).First(&manager)
	if rows.RowsAffected < 1 {
		return false
	}
	return true
}
